﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace DreamShieldBinding
{
    /// <summary>
    /// DreamShield's Project in XML Format
    /// </summary>
    public class DSXProject : DSXBaseObject
    {
        #region Constructor

        /// <summary>
        /// Create a new instance of DreamShield's Xml Project
        /// </summary>
        public DSXProject()
            : base(CreateEmptyProject())
        {
        }

        /// <summary>
        /// Create a new instance of DreamShield's Xml Project from a root node passed in argument
        /// (it must be a DreamShieldProject)
        /// </summary>
        /// <param name="root">Root of the xml tree to parse the project from</param>
        public DSXProject(XmlNode root)
            : base(root)
        {
            if (root == null)
                throw new ArgumentNullException("root");
            if (!root.Name.Equals("DreamShieldProject"))
                throw new ArgumentException("Invalid project file");
        }

        #endregion

        #region Default Project

        public static XmlNode CreateEmptyProject()
        {
            //TODO : To improve
            string default_project = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<DreamShieldProject version=\"1\" generator=\"SharpDevelop\">";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(default_project);
            return doc.SelectSingleNode("DreamShieldProject");
        }

        #endregion

        #region Save ...

        public virtual void Save(Stream output)
        {
            if (output == null)
                throw new ArgumentNullException("output");
            
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.CheckCharacters = false;
            settings.Encoding = Encoding.UTF8;

            var writer = XmlWriter.Create(output, settings);

            Node.WriteTo(writer);
        }

        #endregion

        #region Properties

        public virtual XmlNode ProjectRoot
        {
            get { return Node; }
        }

        #endregion
    }
}
